package org.atf.services;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.directwebremoting.impl.DaemonThreadFactory;

public class ExecutorContextListener implements ServletContextListener {
	private  ExecutorService executor;
	
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("Shuting down the Executor");
		executor.shutdownNow();
	}

	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		ServletContext context = arg0.getServletContext();
		int nr_executors = 1;
		ThreadFactory daemonFactory = new DaemonThreadFactory();
		try {
            nr_executors = Integer.parseInt(context.getInitParameter("nr-executors"));
        } catch (NumberFormatException ignore ) {}
		if(nr_executors <= 1) {
			executor = Executors.newSingleThreadExecutor(daemonFactory);
		} else {
	        executor = Executors.newFixedThreadPool(nr_executors,daemonFactory);
	    }
		System.out.println("started the Executor");
		 context.setAttribute("ATF_EXECUTOR", executor);
	}

}
